// pages/order/pre-order/pre-order.js

//普通下单
//pages/order/pre-order/pre-order?goodList=xx
//农技指导界面下单
//pages/order/pre-order/pre-order?goodList=xx&appid=12&planid=123

// goodItem: {
//   "cardId": "85214",
//   "goodId": "1212",
//   "skuId": "45646",
//   "buyCount": 10 ,
//   "goodName": "史丹利复合肥",
//   "nutrient": "12-7-6总养分>25%",
//   "thumbUrl": "www.baidu.com",
//   "basePrice": "300.00",
//   "vipPrice": "100.00",
// }
var httpUtil = require('../../../utils/httpUtil.js')
var uiUtil = require('../../../utils/uiUtil.js')
var util = require('../../../utils/util.js')
// var emptyUtil = require('../../templates/empty/empty.js')
const app = getApp()
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    identity: null,

    goodList: [],

    goodCount: 0, //商品总件数（）

    takeAdress: null, //收货地址
    payTypeList: null, //支付类型
    payData: null, //付款信息

    creditBtn: 0, //信用支付按钮显示0不显示1显示
    creditBtnSelected: 0, //可用授信金额//0不勾选1勾选
    creditAmount: 0, //可用授信金额

    //农技指导下单使用
    appId: null,
    planId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this
    try {
      var goodList = JSON.parse(decodeURIComponent(options.goodList))
      var appId = options.appid || null
      var planId = options.planid || null
      this.setData({
        goodList: goodList,
        appId: appId,
        planId: planId
      })
    } catch (e) {}

    this.requestPreOrderData()
    that.setData({
      identity: app.globalData.identity
    })
  },
  onShareAppMessage: function(res) {
    return util.handleShareApp()
  },
  /**
   * 结果返回-地址选择
   */
  onResultAddressSelected(address) {
    console.log(address)
    if (!address) {
      return
    } else {
      this.setData({
        takeAdress: address
      })
      if (this.data.payData) {
        that.requestCalcuAmount(this.data.payData.payTypeId)
      }
    }
  },


  /**
   * 获取预下单信息
   */
  requestPreOrderData() {
    uiUtil.showLoading("加载中..")
    var goodList = this.data.goodList
    var length = goodList.length
    var requestGoodList = []
    var goodCount = 0;

    for (var i = 0; i < length; i++) {
      var goodItem = goodList[i]
      goodCount = goodCount + Number(goodItem.buyCount)
      var requestItem = {
        cardId: goodItem.cardId,
        goodId: goodItem.goodId,
        skuId: goodItem.skuId,
        buyCount: goodItem.buyCount
      }
      requestGoodList.push(requestItem)
    }
    this.setData({
      goodCount: goodCount
    })

    httpUtil.PostRequest("pre_submit_order", {
      goodList: requestGoodList
    }, {
      success(res) {
        uiUtil.hideLoading();
        that.setData({
          takeAdress: res.takeAdress,
          payTypeList: res.payTypeList,
          payData: res.payData,
          creditBtn: res.creditBtn ? res.creditBtn : '0',
          creditBtnSelected: res.creditBtnSelected ? res.creditBtnSelected : '0',
          creditAmount: res.creditAmount ? res.creditAmount : '0'
        })
      },
      fail(code, res) {
        uiUtil.showToast(res || "加载失败,请稍候重试")
      },
      complete() {}
    })
  },
  /**
   * 根据支付方式计算金额
   */
  requestCalcuAmount(payTypeId) {
    if (!this.data.takeAdress) {
      uiUtil.showToast("请设置收货地址")
      return
    }
    var addressId = this.data.takeAdress.addressId

    uiUtil.showLoading("请稍候..")
    var goodList = this.data.goodList
    var length = goodList.length
    var requestGoodList = []

    for (var i = 0; i < length; i++) {
      var goodItem = goodList[i]
      var requestItem = {
        cardId: goodItem.cardId,
        goodId: goodItem.goodId,
        skuId: goodItem.skuId,
        buyCount: goodItem.buyCount
      }
      requestGoodList.push(requestItem)
    }
    var useCredit = '0'
    if (that.data.creditBtnSelected == '1') {
      useCredit = '1'
    }

    httpUtil.PostRequest("calcu_order_amount", {
      payTypeId: payTypeId,
      goodList: requestGoodList,
      creditBtnSelected: useCredit,
      addressId: addressId
    }, {
      success(res) {
        uiUtil.hideLoading()
        that.setData({
          payData: res,
          creditBtn: res.creditBtn ? res.creditBtn : '0'
        })
      },
      fail(code, res) {
        uiUtil.showToast(res || "加载失败,请稍候重试")
      },
      complete() {}
    })
  },

  /**
   * 正式下单
   */
  requestSubmitOrder() {
    that = this;
    if (!this.data.takeAdress) {
      uiUtil.showToast("请设置收货地址")
      return
    }
    if (!this.data.payData) {
      uiUtil.showToast("请设置支付方式")
      return
    }

    var addressId = this.data.takeAdress.addressId
    var payTypeId = this.data.payData.payTypeId

    uiUtil.showLoading("请稍候..")
    var goodList = this.data.goodList
    var length = goodList.length
    var requestGoodList = []

    for (var i = 0; i < length; i++) {
      var goodItem = goodList[i]
      var requestItem = {
        cardId: goodItem.cardId,
        goodId: goodItem.goodId,
        skuId: goodItem.skuId,
        buyCount: goodItem.buyCount
      }
      requestGoodList.push(requestItem)
    }

    var useCredit = '0'
    if (that.data.creditBtn == '1' && that.data.creditBtnSelected == '1') {
      useCredit = '1'
    }

    httpUtil.PostRequest("submit_order_pay", {
      goodList: requestGoodList,
      addressId: addressId,
      payTypeId: payTypeId,
      creditBtnSelected: useCredit
    }, {
      success(res) {
        if (that.data.appId && that.data.planId) {
          that.requestLinkTechOrder(res)
        } else {
          uiUtil.hideLoading();
          that.jumpPageAfterSubmitOrder(res)
        }
      },
      fail(code, res) {
        uiUtil.showToast(res || "加载失败,请稍候重试")
      },
      complete() {}
    })
  },

  /**
   * 支付方式点击
   */
  onPaytypeClick() {
    var list = []
    var payList = this.data.payTypeList;
    for (var i = 0; i < payList.length; i++) {
      var item = payList[i]
      list.push(item.typeName)
    }
    wx.showActionSheet({
      itemList: list,
      success(res) {
        that.requestCalcuAmount(that.data.payTypeList[res.tapIndex].typeId)
      }
    })
  },

  /**
   * 授信额度点击
   */
  onCreditClick() {
    var creditBtnSelected = this.data.creditBtnSelected
    this.setData({
      creditBtnSelected: creditBtnSelected == '1' ? '0' : '1'
    })
    if (this.data.payData) {
      that.requestCalcuAmount(this.data.payData.payTypeId)
    }
  },

  /**
   * 关联农技指导订单
   */
  requestLinkTechOrder(orderData) {
    httpUtil.PostRequestHeaderApp("plan_click_order", {
      appId: that.data.appId,
      planId: that.data.planId,
      sellOrderNos: [orderData.orderId],
    }, {
      success(res) {},
      fail(code, res) {},
      complete() {
        uiUtil.hideLoading()
        that.jumpPageAfterSubmitOrder(orderData)
      }
    })
  },

  /**
   * 提交订单成功后界面跳转
   */
  jumpPageAfterSubmitOrder(orderData) {
    var payTypeId = this.data.payData.payTypeId
    if (payTypeId == "online_pay") { //线上支付
      let orderChildStatus = orderData.orderStatus;
      if (orderChildStatus == "noPay") {
        wx.redirectTo({
          url: '/pages/order/online-order/online-order?orderId=' + orderData.orderId
        })
      } else {
        wx.redirectTo({
          url: '/pages/order/pre-status/pre-status?orderResult=' + encodeURIComponent(JSON.stringify(orderData)),
        })
      }
    } else {
      wx.redirectTo({
        url: '/pages/order/pre-status/pre-status?orderResult=' + encodeURIComponent(JSON.stringify(orderData)),
      })
    }
  }
})